package java_game;

import java.util.ArrayList;
import java.util.List;

/**
 * 寻路
 */

public class Demo001 {
    private static Node[][] body = new Node[10][10];

    private Node nodeStart = new Node(0, 0);
    private Node nodeEnd = new Node(5, 5);


    // 节点
    class Node {
        int x = 0;
        int y = 0;
        List<Node> pathList = new ArrayList();

        Node(int x, int y) {
            this.x = x;
            this.y = y;
            pathList.add(this);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Node node = (Node) o;
            if (x != node.x) return false;
            return y == node.y;
        }

        @Override
        public int hashCode() {
            int result = x;
            result = 31 * result + y;
            return result;
        }

        @Override
        public String toString() {
            return "(" + this.x + "," + this.y + ")";
        }

        public void findEnd(Node nodeEnd) {
            // 可行节点
            List<Node> nodeAble = new ArrayList();
            if (this.pathList.indexOf(new Node(this.x + 1, this.y)) == -1) nodeAble.add(new Node(this.x + 1, this.y));
            if (this.pathList.indexOf(new Node(this.x - 1, this.y)) == -1) nodeAble.add(new Node(this.x - 1, this.y));
            if (this.pathList.indexOf(new Node(this.x, this.y + 1)) == -1) nodeAble.add(new Node(this.x, this.y + 1));
            if (this.pathList.indexOf(new Node(this.x, this.y - 1)) == -1) nodeAble.add(new Node(this.x, this.y - 1));
            // 挑选并转换
            Node newNode = null;
            if (nodeAble.indexOf(nodeEnd) != -1) {
                newNode = nodeAble.get(nodeAble.indexOf(nodeEnd));
            }
            if (null == newNode) {
                newNode = nodeAble.get(((int) (Math.random() * 100)) % nodeAble.size());
            }
            pathList.add(newNode);
            System.out.println(this.toString() + " --> " + newNode.toString());
            this.x = newNode.x;
            this.y = newNode.y;
        }
    }


//    // 绘制
//    private void draw() {
//        for (Node[] cells : body) {
//            for (Node cell : cells) {
//                System.out.print(String.format("【%s】", cell));
//            }
//            System.out.println();
//        }
//    }

    public static void main(String[] arge) {
        Demo001 demo = new Demo001();
//        demo.draw();

        demo.nodeStart.findEnd(demo.nodeEnd);
        demo.nodeStart.findEnd(demo.nodeEnd);
        demo.nodeStart.findEnd(demo.nodeEnd);
        demo.nodeStart.findEnd(demo.nodeEnd);
        demo.nodeStart.findEnd(demo.nodeEnd);
        demo.nodeStart.findEnd(demo.nodeEnd);
        demo.nodeStart.findEnd(demo.nodeEnd);
    }
}
